import { Router, Request, Response } from 'express';
import { UserModel } from '../models/user.model';
const jwt = require('jsonwebtoken');
import { authenticateToken, addToBlacklist } from '../middlewares/auth.middleware';

const router = Router();

//用户登录
router.post('/login', async (req: Request, res: Response) => {
  try {
    const user = await UserModel.findByUsername(req.body.username);
    if (!user) {
      res.status(401).json({ code: 0, message: '登录失败,账号或密码错误' });
      return;
    }
    const [storedSalt, storedHash] = user.password.split(':');
    const crypto = require('crypto');
    //需要使用storedSalt和req.body.password计算出的hash进行比对
    const newHash = crypto.pbkdf2Sync(req.body.password, storedSalt, 10000, 64, 'sha512').toString('hex');
    if (user && newHash === storedHash) {
      const token = jwt.sign(
        { userId: user.id, username: user.username },
        process.env.JWT_SECRET || 'default_secret',
        { expiresIn: '1h' }
      );
      res.json({ 
        code: 1, 
        message: '登录成功', 
        data: {
          user,
          token
        }
      });
    } else {
      res.status(401).json({  code: 0, message: '登录失败,账号或密码错误' });
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ error: message });
  }
});

// 获取所有用户 (需要认证)
router.get('/', authenticateToken, async (req: Request, res: Response) => {
  try {
    const users = await UserModel.findAll();
    res.json(users);
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ error: message });
  }
});

// 获取单个用户 (需要认证)
router.get('/:username', authenticateToken, async (req: Request, res: Response) => {
  try {
    const user = await UserModel.findByUsername(String(req.params.username));
    if (user) {
      res.json(user);
    } else {
      res.status(404).json({ error: 'User not found' });
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ error: message });
  }
});

// 创建用户
router.post('/addUser', async (req: Request, res: Response) => {
  try {
    //首先判断用户是否存在
    const user = await UserModel.findByUsername(req.body.username);
    if (user) {
      res.status(400).json({code:0,message:`用户${req.body.username}已存在` });
      return;
    }
    const id = await UserModel.create(req.body);
    res.status(201).json({code:1,message:'创建成功',data:id });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ error: message });
  }
});


// 更新用户
// router.put('/:id', async (req: Request, res: Response) => {
//   try {
//     const success = await UserModel.update(Number(req.params.id), req.body);
//     if (success) {
//       res.json({ success: true });
//     } else {
//       res.status(404).json({ error: 'User not found' });
//     }
//   } catch (error) {
//     const message = error instanceof Error ? error.message : 'Unknown error';
//     res.status(500).json({ error: message });
//   }
// });

// 用户登出
router.post('/logout', authenticateToken, async (req: Request, res: Response) => {
  try {
    const token = req.headers['authorization']?.split(' ')[1];
    if (!token) {
      return res.status(400).json({ code: 0, message: '无效令牌' });
    }
    
    // 计算token剩余有效期(秒)
    //decoded为jwt解码后的对象
    const decoded = jwt.decode(token);
    //expiresIn为剩余有效期(秒)
    const expiresIn = decoded?.exp ? Math.max(0, decoded.exp - Math.floor(Date.now() / 1000)) : 3600;
    
    await addToBlacklist(token, expiresIn);
    res.json({ code: 1, message: '登出成功' });
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ code: 0, message });
  }
});

// 删除用户
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const success = await UserModel.delete(Number(req.params.id));
    if (success) {
      res.json({ success: true });
    } else {
      res.status(404).json({ error: 'User not found' });
    }
  } catch (error) {
    const message = error instanceof Error ? error.message : 'Unknown error';
    res.status(500).json({ error: message });
  }
});

export default router;
